//
//  EFSPreloadConfig.m
//  p4
//
//  Created by YANG Yuxin on 1/29/15.
//  Copyright (c) 2015 com.baidao. All rights reserved.
//

#import "EFSPreloadConfig.h"
//#import "NSUserDefaults+EFS.h"
#import "NSUserDefaults+YS.h"
//#import "EFSServiceManager.h"
#import "YSServiceManager.h"
//#import <MobClick.h>

#import <UMMobClick/MobClick.h>
#import <Foundation/Foundation.h>
#import "EFSConfigManager.h"

NSString * FullKey(NSString *key) {
    NSString *serviceRoutePrefix = @"efs";
//    if ([EFSServiceManager sharedServiceManager].isYG) {
//        serviceRoutePrefix = @"efs";
//    }
    NSString *fullKey = [NSString stringWithFormat:@"%@.%@", serviceRoutePrefix, key];
    return fullKey;
}

id P(NSString *key) {
    return P2(FullKey(key));
}

id P2(NSString *fullKey) {
    
    id result = nil;
    
    NSString *remoteResultStr = nil;
    
    if (remoteResultStr != nil) {
        NSError *error = nil;
        id resultObj = [NSJSONSerialization JSONObjectWithData:[remoteResultStr dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments error:&error];
        if (error == nil) {
            result = resultObj;
        } else {
            result = remoteResultStr;
        }
    }
    
    if (result == nil) {
        // try to get result from local plist
        NSDictionary *localDic = [[NSUserDefaults userDefaultWithGroup] objectForKey:kDefaultPreloadConfigKey];
        result = localDic[fullKey];
    }
    return result;
}


id P3(NSString *mFullkey, NSString *mRealm) {
    id result = nil;
    
    result = [[EFSConfigManager sharedManager] configValueForKey:FullKey(mFullkey) withRealm:mRealm];
    if (result) return result;

    return P(mFullkey);
}

@implementation EFSPreloadConfig

+ (void)registerPreloadConfig {
    NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"defaultConfig" ofType:@"plist"];
    NSDictionary *localDic = [NSDictionary dictionaryWithContentsOfFile:plistPath];
    [[NSUserDefaults userDefaultWithGroup] registerDefaults:@{kDefaultPreloadConfigKey: localDic}];
}
    
@end
